package game.module.item.dao;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

import game.module.template.ShopTemplate;
import lion.common.Reloadable;

public class ShopTemplateCache implements Reloadable {

	private static Logger logger = LoggerFactory.getLogger(ShopTemplate.class);

	static class SingletonHolder {
		static ShopTemplateCache instance = new ShopTemplateCache();
	}

	public static ShopTemplateCache getInstance() {
		return SingletonHolder.instance;
	}

	private transient List<ShopTemplate> templateList;

	private transient Map<String, ShopTemplate> iosIdMap;

	private transient Map<Integer, ShopTemplate> shopMap = new ConcurrentHashMap<>();

	@Override
	public void reload() {

		try {
			String jsonStr = Files.asCharSource(new File("data/shop.json"), Charset.forName("UTF-8")).read();
			ObjectMapper mapper = new ObjectMapper();
			templateList = mapper.readValue(jsonStr, new TypeReference<List<ShopTemplate>>() {
			});
			logger.info("size={}", templateList.size());
			Map<String, ShopTemplate> iosIdMapTmp = new HashMap<>();
			for (ShopTemplate shopTemplate : templateList) {
				iosIdMapTmp.put(shopTemplate.getIosid(), shopTemplate);
				shopMap.put(shopTemplate.getId(), shopTemplate);
			}
			iosIdMap = iosIdMapTmp;
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public boolean containsShopTemplateIndex(int index) {
		return index < templateList.size();
	}

	public ShopTemplate getTemplate(int index) {
		return (templateList.get(index));

	}

	public ShopTemplate getShopTemplateByShopId(int shopId) {
		return shopMap.get(shopId);
	}

	public static void main(String[] args) {
		new ShopTemplateCache().reload();
	}

	public ShopTemplate getIosRechargeTemplateById(String iosId) {
		return iosIdMap.get(iosId);
	}

}
